package model.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import model.Account;
import model.DataAccess;

public class AccountDAO {
	private DataAccess dao;

	public AccountDAO() {
		dao = new DataAccess();
	}

	public List<String> getAllUserName() {
		try {
			Connection connection = dao.getConnection();
			String sql = "select * from account;";
			ResultSet result = connection.createStatement().executeQuery(sql);
			List<String> list = new ArrayList<>();
			while (result.next()) {
				list.add(result.getString("username"));
			}
			dao.disConnect(connection);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Account getAccount(String username, int pin) {
		try {
			Connection connection = dao.getConnection();
			String sql = "select * from account where username='" + username
					+ "' and pincode=" + pin + ";";
			ResultSet result = connection.createStatement().executeQuery(sql);
			Account account = null;
			if (result.next()) {
				account = new Account();
				account.setUsername(result.getString("username"));
				account.setPassword(result.getString("password"));
				account.setPin(result.getInt("pincode"));
				account.setOneTimePassword(result.getString("onetimepass"));
			}
			dao.disConnect(connection);
			return account;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public Account getAccount(String username) {
		try {
			Connection connection = dao.getConnection();
			String sql = "select * from account where username='" + username
					+ "';";
			ResultSet result = connection.createStatement().executeQuery(sql);
			Account account = null;
			if (result.next()) {
				account = new Account();
				account.setUsername(result.getString("username"));
				account.setPassword(result.getString("password"));
				account.setPin(result.getInt("pincode"));
				account.setOneTimePassword(result.getString("onetimepass"));
			}
			dao.disConnect(connection);
			return account;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public void updateAccount(Account account) {
		try {
			Connection connection = dao.getConnection();
			String sql = "update account set onetimepass='"
					+ account.getOneTimePassword() + "' where username='"
					+ account.getUsername() + "';";
			connection.createStatement().execute(sql);
			dao.disConnect(connection);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
